package com.um.jdy.app.shop.factory.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.um.jdy.app.shop.activity.Activity;
import com.um.jdy.app.shop.activity.impl.FullReduceActivityImpl;
import com.um.jdy.app.shop.activity.impl.GroupActivityImpl;
import com.um.jdy.app.shop.activity.impl.SeckillActivityImpl;
import com.um.jdy.app.shop.entity.bo.ActivityBO;
import com.um.jdy.app.shop.factory.ActivityFactory;
import com.um.jdy.common.market.service.ActivityService;
import com.um.jdy.common.shop.enums.ActivityEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 活动工厂实现类
 *
 * @author 邓南辉
 * 日期 2021/6/28
 * 版权所有 广州优匠科技有限公司
 */
@Service
@Transactional
public class ActivityFactoryImpl implements ActivityFactory {

    @Autowired
    ActivityService activityService;

    @Autowired
    AutowireCapableBeanFactory beanFactory;

    @Autowired
    DefaultListableBeanFactory defaultListableBeanFactory;

    @Override
    public List<Activity> createActivities() {
        List<Activity> activityList = new ArrayList();

        List<com.um.jdy.common.market.entity.po.Activity> list = activityService.getListBySqlName("get_activity_list_in_progress",new Object[]{activityService.getComId()}); //正在进行中的活动列表

        for(com.um.jdy.common.market.entity.po.Activity item : list){

            ActivityBO activityBO = BeanUtil.toBean(item, ActivityBO.class);

            Activity activity = this.getActivity(activityBO);
            if(null != activity){
                activityList.add(activity);
            }
        }

        return activityList;
    }


    private Activity getActivity(ActivityBO activityBO) {
        Activity activity;
        switch (ActivityEnum.Type.valueOf(activityBO.getType())){
            case Seckill:
                activity = new SeckillActivityImpl();
                break;
            case Group:
                activity = new GroupActivityImpl();
                break;
            case Reduce:
                activity = new FullReduceActivityImpl();
                break;
            default:
                return null;
        }

        //将new出的对象放入Spring容器中注入依赖
        if(null != activity){
            String beanName = System.currentTimeMillis() + "-" + RandomUtil.randomInt(10000);
            defaultListableBeanFactory.registerSingleton(beanName,activity);
            beanFactory.autowireBean(activity);
        }

        activity.setActivityEntity(activityBO);
        return activity;
    }
}

